//
//  LNNetworkTools.swift
//  727-黑马08微博-测试
//
//  Created by apple on 15/7/30.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking
 /// 错误的类别标记
private let HMErrorDomainName = "com.linan08104.error.network"
 /// 网络访问错误信息-枚举，是定义一组类似的值
/// Swift中枚举可以定义函数和属性，跟‘类'有点像
private enum LNNetworkError: Int {
    case emptyDataError = -1
    case emptyTokenError = -2
    
/// 错误描述
    private var errorDescription: String {
        switch self {
        case .emptyDataError: return "空数据"
        case .emptyTokenError: return "Token 为空"
        }
    }
    
/// 根据枚举类型，返回对应的错误
    private func error() -> NSError {
        return NSError(domain: HMErrorDomainName, code: rawValue, userInfo: [HMErrorDomainName: errorDescription])
    }
}

 /// 网络访问方法
private enum LNNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}



class LNNetworkTools: AFHTTPSessionManager {
  
    

    //    应用程序信息
    private let clientId = "2465228863"
    private let appSecret = "5a46b3141e8f4f1e66abb4e701fe2674"
    /// 回调地址
    let redirectUri = "http://www.baidu.com"
  
//    MARK:- 类型定义
    /// 网络回调类型别名
    typealias LNNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?)->()

    //    单例
    static let  sharedTools: LNNetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = LNNetworkTools(baseURL: baseURL)
        //        设置数据解析类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return tools
        }()
    
//  检查并生成token字典
    private func tokenDict(finished: LNNetFinishedCallBack) -> [String: AnyObject]? {
//        判断token是否存在
        if LNUserAccount.sharedAccount?.access_token == nil {
//            错误回调， token为空
            let error = LNNetworkError.emptyTokenError.error()
            print(error)
            finished(result: nil, error: error)
            return nil
        }
//        生成token字典返回
        return ["access_token": LNUserAccount.sharedAccount!.access_token!]
        
    
    }
    
//    MARK： - 发布微博
    func sendStatus(status: String, finished: LNNetFinishedCallBack) {
        guard var params = tokenDict(finished) else {
            return
        }
        params["status"] = status
//        POST发布微博
        request(LNNetworkMethod.POST, urlString: "2/statuses/update.json", params: params, finished: finished)
    }
 
    
    
//    MARK: - 加载微博数据
    /**
    since_id    则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
    max_id      则返回ID`小于或等于max_id`的微博，默认为0
    */
    func loadStatus(since_id: Int, max_id: Int,finished:LNNetFinishedCallBack) {
//        判断token是否存在，为nil直接返回
//        guard是swift2.0的新语法，跟if let刚好相反
//        let 获得的变量，后续可以直接使用，而且一定不为nil
        guard var params = tokenDict(finished) else {
//            params在此为nil, 一般直接返回
            return
        }
        if since_id > 0 {
            params["since_id"] = since_id
            
        }
        if max_id > 0 {
            params["max_id"] = max_id - 1
            
        }
        
//        代码运行至此，params一定有值
    let urlString = "2/statuses/home_timeline.json"
        request(LNNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
    


//    MARK: -加载用户数据
    func loadUserInfo(uid: String, finished: LNNetFinishedCallBack) {
//        判断token是否存在
//
        guard var params = tokenDict(finished) else {
            //            params在此为nil, 一般直接返回
            return
        }
        let urlString = "2/users/show.json"

        params["uid"] = uid
//        发送网络请求

        request(LNNetworkMethod.GET, urlString: urlString, params:params, finished: finished)
        
    }
    
    
    
    
    
/// 返回OAuth授权地址
    func oauthUrl() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
/// 加载Token
    func loadAccessToken(code:String, finished: LNNetFinishedCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
         "client_secret": appSecret,
         "grant_type": "authorization_code",
         "code": code,
          "redirect_uri":redirectUri]
        request(LNNetworkMethod.POST, urlString: urlString, params: params, finished: finished)
    
        

        
    }
//    MARK: - 封装AFN网络方法，便于替换网络访问方法，第三方框架的网络代码全部集中在此
    
    
    private func request(method: LNNetworkMethod, urlString: String, params:[String: AnyObject], finished: LNNetFinishedCallBack) {
//        1.定义成功的闭包
        // 1. 定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finished(result: result, error: nil)
            } else {
                // 没有错误，同时没有结果
                print("没有数据 \(method) Request \(urlString)")
                
                finished(result: nil, error: LNNetworkError.emptyDataError.error())
            }
        }
        
        // 2. 定义失败的闭包
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            print(error)
            
            finished(result: nil, error: error)
        }
        
        
//        3. 根据method来选择执行的方法
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        
        }
        
        
    }
    
        
    

}






















